package com.example.home1023;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

public class FruitAdapter extends ArrayAdapter<Fruit> {
    public FruitAdapter(@NonNull Context context, int resource, @NonNull List<Fruit> objects) {
        super(context, resource, objects);
    }

    public View getview(int position, @Nullable View convertView,@NonNull ViewGroup parent) {
        Fruit fruit = getItem(position);
        View view;
        //新增一个内部美ViewHolder
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(R.layout.activity_main,parent,false);
            viewHolder  = new ViewHolder();
//分别获取imageviewutextview
            viewHolder.fruitimage = view.findViewById(R.id.fruit_imag);
            viewHolder.fruitname = view.findViewById(R.id.fruit_name);
            viewHolder.fruitprice = view.findViewById(R.id.fruit_price);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.fruitimage.setImageResource(fruit.getImageId());
        viewHolder.fruitname.setText(fruit.getName());
        viewHolder.fruitprice.setText(fruit.getPrice());
        return view;

        }


    private class ViewHolder{
        ImageView fruitimage;
        TextView fruitname;
        TextView fruitprice;
    }

}
